package org.fluidripple.socket.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.fluidripple.socket.inbound.ClientEventHandler;
import org.fluidripple.socket.operation.CKSUMCalculator;
import org.fluidripple.socket.operation.ChannelOperation;
import org.fluidripple.socket.session.Session;
import org.fluidripple.socket.session.SessionManager;
import org.fluidripple.socket.stickhalf.FixedLengthDecoderImpl;
import org.fluidripple.socket.wrapper.DataWrapper;
import org.springframework.stereotype.Component;

/**
 * 设置采样频率
 */
@Slf4j
@Component
public class SamplingFrequencySetProtocol extends Protocol{

    private int samplingFrequency;

    public SamplingFrequencySetProtocol() {
    }

    public SamplingFrequencySetProtocol(int samplingFrequency) {
        this.samplingFrequency = samplingFrequency;
    }

    @Override
    public void writer(Channel channel) {
        ChannelOperation.replaceChannelHandler(channel, ClientEventHandler.name, FixedLengthDecoderImpl.name,new FixedLengthDecoderImpl(6));
        byte[] bytes = ByteBufUtil.decodeHexDump("F0C104D0");
        ByteBuf buffer = Unpooled.buffer(6);
        buffer.writeBytes(bytes);
        buffer.writeByte(samplingFrequency);

        ByteBuf checkBuf = Unpooled.buffer(3);
        checkBuf.writeBytes(buffer,2,2);
        checkBuf.writeByte(samplingFrequency);
        int checksum = CKSUMCalculator.calculateChecksum(checkBuf.array());
        buffer.writeByte(checksum);
        channel.writeAndFlush(buffer);
    }

    @Override
    public void toDecode(DataWrapper dataWrapper) {
        log.info("SamplingFrequencySetProtocol toDecode:{}",ByteBufUtil.hexDump(dataWrapper.getBuf()));
    }
}
